package tech.wetech.admin3.controller;

import cn.hutool.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.wetech.admin3.sys.exception.AooUserException;
import tech.wetech.admin3.sys.model.AooAnotherSomeone;
import tech.wetech.admin3.sys.model.DID;
import tech.wetech.admin3.sys.service.AooAnotherSomeoneService;
import tech.wetech.admin3.util.CustomResponse;
import tech.wetech.admin3.util.DIDCreateUtil;
import tech.wetech.admin3.util.HashUtil;
import tech.wetech.admin3.util.LianduAPIUtils;

import java.util.*;

@RestController
@RequestMapping("/Digital")
public class AooAnotherSomeoneController {
  private DIDCreateUtil didCreateUtil;
  private AooAnotherSomeoneService anotherSomeoneService;
  private HashUtil hashUtil;
  private LianduAPIUtils lianduAPIUtil;

  public AooAnotherSomeoneController(
    DIDCreateUtil didCreateUtil,
    AooAnotherSomeoneService anotherSomeoneService,
    HashUtil hashUtil,
    LianduAPIUtils lianduAPIUtil
  ) {
    this.didCreateUtil = didCreateUtil;
    this.anotherSomeoneService = anotherSomeoneService;
    this.hashUtil = hashUtil;
    this.lianduAPIUtil = lianduAPIUtil;
  }

  @PostMapping("/anothersomeone")
  public ResponseEntity<?> createAnotherSomeone(
    @RequestParam("owner") String owner,
    @RequestParam("ownerIdNo") String ownerIdNo,
    @RequestParam("email") String email,

    @RequestParam("name") String name,
    @RequestParam("idNo") String idNo,
    @RequestParam("mobile") String mobile,

    @RequestParam("digitalName") String digitalName,
    @RequestParam(value = "feature", required = false) String feature,
    @RequestParam(value = "purpose", required = false) String purpose,

    @RequestParam("images") MultipartFile[] images,
    @RequestParam(value = "modelFiles", required = false) MultipartFile[] modelFiles,
    @RequestParam(value = "signFileUrl", required = false) String signFileUrl
  ) {
    try {
      AooAnotherSomeone anotherSomeone = anotherSomeoneService.createAnotherSomeone(
        owner, ownerIdNo, email, name, idNo, digitalName, mobile, feature, purpose, modelFiles, images, signFileUrl
      );
      return ResponseEntity.ok(new CustomResponse.r1<>("提交成功", true, anotherSomeone));
    } catch (AooUserException e) {
      return ResponseEntity.ok(new CustomResponse.r1<>(e.getMessage(), false, null));
    }
  }

  @PutMapping("someone/update/agree-or-not")
  public ResponseEntity<?> updateAgree(
    @RequestParam("id") Integer id,
    @RequestParam("agreeOrNot") Integer agreeOrNot,
    @RequestParam("signFileUrl") String signFileUrl
  ) {
    if (!agreeOrNot.equals(1) && !agreeOrNot.equals(2)) {
      return ResponseEntity.badRequest().body(new CustomResponse.r1("状态值无效，只能为1或2", false, null));
    }
    boolean flag = anotherSomeoneService.updateAgreeOrNot(id, agreeOrNot, signFileUrl);
    if (flag) {
      AooAnotherSomeone anotherSomeone = anotherSomeoneService.findById(id);
      return ResponseEntity.ok(new CustomResponse.r1("成功更新 agreeOrNot", true, anotherSomeone));
    } else {
      return ResponseEntity.ok(new CustomResponse.r1("未找到该审核资料,请检查email是否正确", false, null));
    }
  }

  @Transactional
  @PutMapping("/reset/status-someone")
  public ResponseEntity<?> resetStatus(
    @RequestParam("uuid") UUID uuid,
    @RequestParam("newStatus") Integer newStatus,
    @RequestParam(value = "checkDesc", required = false) String checkDesc
  ) {
    // 对newStatus的验证
    if (newStatus < 1 || newStatus > 3) {
      return ResponseEntity.badRequest().body(new CustomResponse.r1("状态值无效，只能为1, 2 或3", false, null));
    }

    boolean flag = anotherSomeoneService.resetStatus(uuid, newStatus, checkDesc);
    if (flag) {
      if (newStatus == 2) {  // 审核通过,创建DID
        AooAnotherSomeone anotherSomeone = anotherSomeoneService.findByUuid(uuid);
        String digitalName = anotherSomeone.getDigitalName();
        String owner = anotherSomeone.getOwner();
        String imageUrls = anotherSomeone.getImageUrls();
        String imageHashes = anotherSomeone.getImageHashes();
        String modelFileUrls = anotherSomeone.getModelFileUrls();
        String modelFileHashes = anotherSomeone.getModelFileHashes();

        DID did = didCreateUtil.createDID("z", digitalName, owner, imageUrls, imageHashes, modelFileUrls, modelFileHashes);

        String serial = did.getSerial();
        String didNo = did.getDidNo();
        anotherSomeone.setSerial(serial);
        anotherSomeone.setDidNo(didNo);
//        aooAnotherSomeoneService.update(anotherSomeone);    // 更新操作 等同于注解 @Transactional

        String hashV = hashUtil.getStringHash(serial);
        int timeStamp = (int) (System.currentTimeMillis() / 1000);

        Map<String, Object> datainfo = new HashMap<>();
        datainfo.put("name", did.getName());
        datainfo.put("type", did.getType());
        datainfo.put("serial", did.getSerial());
        datainfo.put("didNo", did.getDidNo());
        datainfo.put("ukey", did.getUkey());
        datainfo.put("txhash", did.getTxhash());

        JSONObject res_saveAuth = lianduAPIUtil.saveAuth(hashV, timeStamp, datainfo.toString()).join();

        if (res_saveAuth.getStr("txhash") != null) {
          did.setTxhash_saveAuth(res_saveAuth.getStr("txhash"));
        } else {
          return ResponseEntity.ok(new CustomResponse.r1("did角色已创建，但上链存证失败", true, did));
        }

        return ResponseEntity.ok(new CustomResponse.r1("审核通过，已创建DID角色", true, did));
      } else if (newStatus == 3) {
        return ResponseEntity.ok(new CustomResponse.r1("审核驳回", true, null));
      } else {
        return ResponseEntity.ok(new CustomResponse.r1("审核中", true, null));
      }
    } else {
      return ResponseEntity.ok(new CustomResponse.r1("未找到该审核资料,请检查id是否正确", false, null));
    }
  }

  @GetMapping("/getall/someone")
  public ResponseEntity<?> getAllDataAgree(
    @RequestParam("page") int page,
    @RequestParam("size") int size,
    @RequestParam(value = "paid", required = false) Boolean paid
  ) {
    List<?> data;
    if (Boolean.TRUE.equals(paid)) {
      data = anotherSomeoneService.findByPaidAndAgreeOrNot(true, 1);
    } else {
      data = anotherSomeoneService.getAllDataAgree();
    }

    int total = data.size();
    int start = page * size;
    int end = Math.min(start + size, total);
    List<Object> paginatedList;

    if (start < total) {
      paginatedList = new ArrayList<>(data.subList(start, end));
    } else {
      paginatedList = new ArrayList<>();
    }

    Map<String, Object> result = new HashMap<>();
    result.put("page", page);
    result.put("size", size);
    result.put("total", total);
    result.put("record", paginatedList);
    return ResponseEntity.ok(new CustomResponse.r1("ok", true, result));
  }

  @GetMapping("/getbyemail/someone")
  public ResponseEntity<?> getByEmail(
    @RequestParam("email") String email  // @PathVariable("email") String email 需要在路径中使用占位符 "/getbyemail/someone/{email}"
  ) {
    List data = anotherSomeoneService.findByEmail(email);
    return ResponseEntity.ok(new CustomResponse.r1("ok", true, data));
  }

}
